﻿using dz.u9.jky.schema.Common;
using dz.u9.jky.schema.Vendor;
using System.Collections.Generic;
using UFIDA.U9.CBO.Pub.Controller;
using UFIDA.U9.ISV.Supplier;


namespace dz.inner.jky.api.service
{
    internal class SupplierService : BaseService
    {
        public U9CResult Add(DzSupplierDTO dto)
        {
            return util.U9Invoke(__Add, dto);
        }

        public void Modify(DzSupplierDTO dto)
        {
            BatchModifySupplierByDTOSV sv = new BatchModifySupplierByDTOSV();

            sv.SupplierDTOs = Convert(dto, Query(dto));

            sv.Do();

        }

        private List<SupplierDTO> Convert(DzSupplierDTO supplier, List<SupplierDTO> target)
        {

            ObjectCopyUtil util = new ObjectCopyUtil();

            List<SupplierDTO> rtn = new List<SupplierDTO>();

            foreach (var item in target)
            {
                SupplierDTO dto = item;
                util.CopyProperty(supplier, ref dto);

                rtn.Add(dto);
            }
            return rtn;
        }
        private U9CResult __Add(DzSupplierDTO dto)
        {
            BatchCreateSupplierByDTOSV sv = new BatchCreateSupplierByDTOSV();

            sv.SupplierDTOs = Convert(dto);

            var rtn =  sv.Do();

            U9CResult result = new U9CResult();

            result.Id = rtn[0].ID;
            result.DocNo = rtn[0].Code;
            result.IsSuccess = true;

            if (result.IsSuccess)
            {
                DocIssueService issueService = new DocIssueService();

                DocIssue issue = new DocIssue();
                issue.FromOrg = dto.Org;
                issue.EntityName = "UFIDA.U9.CBO.SCM.Supplier.Supplier";
                issue.Ids = new List<long>() { result.Id };

                issueService.Issued(issue);
            }

            return result;

        }

        private List<SupplierDTO> Convert(DzSupplierDTO supplier)
        {
            SupplierDTO dto = new SupplierDTO();            

            ObjectCopyUtil util = new ObjectCopyUtil();

            util.CopyProperty(supplier, ref dto);


            List<SupplierDTO> rtn = new List<SupplierDTO>() { dto };

            return rtn;
        }

        private List<SupplierDTO> Query(DzSupplierDTO supplier)
        {
            List<DzSupplierDTO> rtn = new List<DzSupplierDTO>();

            List<string> orgs = util.GetOrgCodes(supplier.Org);

            List<QuerySupplierDTO> querys = new List<QuerySupplierDTO>();

            foreach (var org in orgs)
            {
                QuerySupplierDTO parm = new QuerySupplierDTO();

                parm.Org = new CommonArchiveDataDTO() { Code = org };
                parm.Supplier = new CommonArchiveDataDTO() { Code = supplier.Code };

                querys.Add(parm);
            }

            BatchQuerySupplierByDTOSRV sv = new BatchQuerySupplierByDTOSRV();
            sv.QuerySupplierDTOs = querys;

            return sv.Do();
        }

    }
}
